package com.hgyc.mom.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.hgyc.mom.mes.service.MesWorkshopMachineService;
import com.hgyc.mom.mes.vo.MesWorkshopParam;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.hgyc.mom.mes.mapper.MesWorkshopMapper;
import com.hgyc.mom.mes.entity.MesWorkshop;
import com.hgyc.mom.mes.entity.MesWorkshopMachine;
import com.hgyc.mom.mes.entity.MesWorkshopProduct;
import com.hgyc.mom.mes.service.MesWorkshopProductService;
import com.hgyc.mom.mes.entity.MesWorkshopUser;
import com.hgyc.mom.mes.service.MesWorkshopUserService;
import com.hgyc.mom.mes.vo.MesWorkshopVO;
import com.hgyc.mom.mes.service.MesWorkshopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import com.hgyc.mom.common.exception.BizException;
import org.springframework.util.CollectionUtils;

/**
 * 车间 Service业务层实现
 *
 * @author fwj
 * @since 2025-06-23
 */
@Slf4j
@Service
public class MesWorkshopServiceImpl extends ServiceImpl<MesWorkshopMapper, MesWorkshop> implements MesWorkshopService {

    @Autowired
    private MesWorkshopMachineService mesWorkshopMachineService;
    @Autowired
    private MesWorkshopProductService mesWorkshopProductService;
    @Autowired
    private MesWorkshopUserService mesWorkshopUserService;

    @Override
    public List<MesWorkshop> treeList(MesWorkshopParam mesWorkshopParam) {
        MesWorkshop wmsWarehouse = new MesWorkshop();
        BeanUtils.copyProperties(mesWorkshopParam, wmsWarehouse);
        QueryWrapper<MesWorkshop> wrapper = QueryWrapperUtil.build(wmsWarehouse);
        List<MesWorkshop> list = list(wrapper);
        return this.convertToTree(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWorkshop(MesWorkshopVO mesWorkshopVO) {
        // TODO 其他逻辑
        save(mesWorkshopVO);

        //新增车间建模设备信息
        List<MesWorkshopMachine> addMachines = mesWorkshopVO.getAddMachines();
        if (!CollectionUtils.isEmpty(addMachines)) {
            addMachines.forEach(item -> {
                item.setId(null);
                item.setWorkshopId(mesWorkshopVO.getId());
            });
            mesWorkshopMachineService.saveBatch(addMachines);
        }
        //新增关联产品
        List<MesWorkshopProduct> products = mesWorkshopVO.getAddProducts();
        if (!CollectionUtils.isEmpty(products)) {
            products.forEach(item -> {
                item.setId(null);
                item.setWorkshopId(mesWorkshopVO.getId());
            });
            mesWorkshopProductService.saveBatch(products);
        }
        //新增车间员工
        List<MesWorkshopUser> users = mesWorkshopVO.getAddUsers();
        if (!CollectionUtils.isEmpty(users)) {
            users.forEach(item -> {
                item.setId(null);
                item.setWorkshopId(mesWorkshopVO.getId());
            });
            mesWorkshopUserService.saveBatch(users);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWorkshop(MesWorkshopVO mesWorkshopVO) {
        // TODO 其他逻辑
        updateById(mesWorkshopVO);

        //删除车间建模设备信息
        if (!CollectionUtils.isEmpty(mesWorkshopVO.getDeleteMachineIds())) {
            mesWorkshopMachineService.removeBatchByIds(mesWorkshopVO.getDeleteMachineIds());
        }

        //新增车间建模设备信息
        List<MesWorkshopMachine> addMachines = mesWorkshopVO.getAddMachines();
        if (!CollectionUtils.isEmpty(addMachines)) {
            addMachines.forEach(item -> {
                item.setId(null);
                item.setWorkshopId(mesWorkshopVO.getId());
            });
            mesWorkshopMachineService.saveBatch(addMachines);
        }

        //更新车间建模设备信息
        if (!CollectionUtils.isEmpty(mesWorkshopVO.getUpdateMachines())) {
            List<MesWorkshopMachine> updateMachines = mesWorkshopVO.getUpdateMachines();
            mesWorkshopMachineService.updateBatchById(updateMachines);
        }
        //删除关联产品
        if (!CollectionUtils.isEmpty(mesWorkshopVO.getDeleteProductIds())) {
            mesWorkshopProductService.removeBatchByIds(mesWorkshopVO.getDeleteProductIds());
        }

        //新增关联产品
        List<MesWorkshopProduct> products = mesWorkshopVO.getAddProducts();
        if (!CollectionUtils.isEmpty(products)) {
            products.forEach(item -> {
                item.setId(null);
                item.setWorkshopId(mesWorkshopVO.getId());
            });
            mesWorkshopProductService.saveBatch(products);
        }

        //更新关联产品
        if (!CollectionUtils.isEmpty(mesWorkshopVO.getUpdateProducts())) {
            List<MesWorkshopProduct> updateProducts = mesWorkshopVO.getUpdateProducts();
            mesWorkshopProductService.updateBatchById(updateProducts);
        }
        //删除车间员工
        if (!CollectionUtils.isEmpty(mesWorkshopVO.getDeleteUserIds())) {
            mesWorkshopUserService.removeBatchByIds(mesWorkshopVO.getDeleteUserIds());
        }

        //新增车间员工
        List<MesWorkshopUser> users = mesWorkshopVO.getAddUsers();
        if (!CollectionUtils.isEmpty(users)) {
            users.forEach(item -> {
                item.setId(null);
                item.setWorkshopId(mesWorkshopVO.getId());
            });
            mesWorkshopUserService.saveBatch(users);
        }

        //更新车间员工
        if (!CollectionUtils.isEmpty(mesWorkshopVO.getUpdateUsers())) {
            List<MesWorkshopUser> updateUsers = mesWorkshopVO.getUpdateUsers();
            mesWorkshopUserService.updateBatchById(updateUsers);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeWorkshop(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
        //删除车间建模设备信息
        mesWorkshopMachineService.deleteBatchByParentIds(ids);
        //删除关联产品
        mesWorkshopProductService.deleteBatchByParentIds(ids);
        //删除车间员工
        mesWorkshopUserService.deleteBatchByParentIds(ids);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<MesWorkshop> mesWorkshopList, boolean updateSupport) {
        if (mesWorkshopList == null || mesWorkshopList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + mesWorkshopList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + mesWorkshopList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("车间 导入失败", e);
            throw new BizException("车间 导入失败：" + e.getMessage());
        }
    }

    private List<MesWorkshop> convertToTree(List<MesWorkshop> wmsWarehouseList) {
        Map<Long, List<MesWorkshop>> parentChildrenMap = new HashMap<>();
        for (MesWorkshop mesWorkshop : wmsWarehouseList) {
            Long parentId = mesWorkshop.getParentId();

            // 将当前菜单项添加到父菜单项的子菜单项列表中
            List<MesWorkshop> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
            children.add(mesWorkshop);
            parentChildrenMap.put(parentId, children);

        }
        // 将根节点的子菜单项列表转换为树形结构
        List<MesWorkshop> rootChildren = parentChildrenMap.getOrDefault(0L, new ArrayList<>());
        for (MesWorkshop mesWorkshop : rootChildren) {
            convertToTree(mesWorkshop, parentChildrenMap);
        }
        return rootChildren;
    }

    private void convertToTree(MesWorkshop parent, Map<Long, List<MesWorkshop>> parentChildrenMap) {
        Long parentId = parent.getId();
        List<MesWorkshop> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
        parent.setChildren(children);
        for (MesWorkshop child : children) {
            convertToTree(child, parentChildrenMap);
        }
    }
}